package com.wsoft.cms.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsoft.cms.entity.CmsCategoryEntity;
import com.wsoft.cms.manager.CmsCategoryAuthManager;
import com.wsoft.cms.manager.CmsCategoryManager;
import com.wsoft.cms.mapper.CmsCategoryMapper;
import com.wsoft.cms.query.cate.auth.CateAuthUpdateQuery;
import com.wsoft.cms.query.category.CategoryInsertQuery;
import com.wsoft.cms.query.category.CategoryUpdateQuery;
import com.wsoft.cms.service.ICmsCategoryAuthService;
import com.wsoft.cms.service.ICmsCategoryService;
import com.wsoft.cms.vo.category.CmsCategoryInfoVO;
import com.wsoft.cms.vo.category.CmsCategoryVO;
import com.wsoft.core.utils.LoginUserUtil;
import com.wsoft.core.utils.SqlAuthDisableHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 公告类型表 服务实现类
 * </p>
 *
 * @author juiet
 * @since 2024年11月27日 10:39:16
 */
@Service
public class CmsCategoryServiceImpl extends ServiceImpl<CmsCategoryMapper, CmsCategoryEntity> implements ICmsCategoryService {

    @Resource
    private CmsCategoryManager categoryManager;
    @Resource
    private CmsCategoryAuthManager categoryAuthManager;
    @Resource
    private ICmsCategoryAuthService categoryAuthService;

    /**
     * 新增分类
     *
     * @param query
     * @return
     */
    @Override
    public boolean insertCategory(CategoryInsertQuery query) {
        //生成code
        String maxCode = categoryManager.getMaxCode(query.getPaId());

        CmsCategoryEntity convert = Convert.convert(CmsCategoryEntity.class, query);
        convert.setLevel(null == query.getPaId() ? 1 : 2);
        convert.setCode(maxCode);
        boolean b = categoryManager.save(convert);
        if (b) {
            CateAuthUpdateQuery authQuery = new CateAuthUpdateQuery();
            authQuery.setCategoryId(convert.getId());
            authQuery.setOrgIdList(query.getOrgIdList());
            categoryAuthService.updateCategoryAuth(authQuery);
        }

        return b;
    }

    /**
     * 编辑分类
     *
     * @param query
     * @return
     */
    @Override
    public boolean updateCategory(CategoryUpdateQuery query) {
        CmsCategoryEntity convert = Convert.convert(CmsCategoryEntity.class, query);
        boolean b = categoryManager.updateById(convert);
        if (b) {
            CateAuthUpdateQuery authQuery = new CateAuthUpdateQuery();
            authQuery.setCategoryId(convert.getId());
            authQuery.setOrgIdList(query.getOrgIdList());
            categoryAuthService.updateCategoryAuth(authQuery);
        }
        return b;
    }


    @Override
    public boolean delete(Long id) {
        return categoryManager.deleteById(id);
    }

    @Override
    public CmsCategoryInfoVO get(Long id) {
        return categoryManager.getById(id);
    }


    @Override
    public List<CmsCategoryVO> tree(boolean isUser, String cateId) {
        if (isUser) {
            SqlAuthDisableHolder.open();
        }
        List<CmsCategoryEntity> list = categoryManager.listCategory(isUser);
        if (isUser) {
            HashSet<Long> idSet = new HashSet<>();
            //如果是用户端,则需要按照分类权限表 过滤
            //如果是管理端,则直接走数据权限
            if (StrUtil.isNotBlank(cateId)) {
                String[] split = cateId.split(StrUtil.COMMA);
                for (String str : split) {
                    idSet.add(Long.parseLong(str));
                }
            } else {
                List<Long> categoryId = categoryAuthManager.getByOrgId(LoginUserUtil.getUserInfo().getLoginUserVO().getLoginOrgId());
                SqlAuthDisableHolder.close();

                for (Long id : categoryId) {
                    getParIdList(list, id, idSet);
                }
            }
            list = list.stream().filter(item -> idSet.contains(item.getId())).collect(Collectors.toList());
        }
        List<CmsCategoryEntity> finalList = list;

        return list.stream()
                .filter(item -> null == item.getPaId() || 0 == item.getPaId())
                .sorted(Comparator.comparing(CmsCategoryEntity::getSort, Comparator.nullsLast(Integer::compareTo)))
                .map(item -> buildTree(item, finalList)).collect(Collectors.toList());
    }


    /**
     * 获取上级节点id
     *
     * @param list
     * @param id
     * @param idSet
     */
    public void getParIdList(List<CmsCategoryEntity> list, Long id, HashSet<Long> idSet) {
        if (null == id || 0 == id) {
            return;
        }
        List<CmsCategoryEntity> collect = list.stream().filter(item -> item.getId().equals(id)).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            idSet.add(collect.get(0).getId());
            getParIdList(list, collect.get(0).getPaId(), idSet);
        }
    }

    /**
     * 构建树
     *
     * @param category
     * @param list
     * @return
     */
    private static CmsCategoryVO buildTree(CmsCategoryEntity category, List<CmsCategoryEntity> list) {
        CmsCategoryVO node = Convert.convert(CmsCategoryVO.class, category);

        List<CmsCategoryVO> children = list.stream()
                .filter(item -> category.getId().equals(item.getPaId()))
                .sorted(Comparator.comparing(CmsCategoryEntity::getSort, Comparator.nullsLast(Integer::compareTo)))
                .map(item -> buildTree(item, list)).collect(Collectors.toList());
        node.setChildList(children);
        return node;
    }
}